/**  
* @Title: SeckillServiceImpl.java
* @Package org.seckill.service.Iml
* @Description: TODO(用一句话描述该文件做什么)
* @author lxp  
* @date 2016年9月21日 下午2:50:37
* @version V1.0  
*/ 
package org.seckill.service.Iml;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.seckill.dao.SeckillDao;
import org.seckill.dao.SuccessKilledDao;
import org.seckill.dao.cach.RedisDao;
import org.seckill.dto.Exposer;
import org.seckill.dto.SeckillExecution;
import org.seckill.entity.Seckill;
import org.seckill.entity.Successkilled;
import org.seckill.enums.SeckillStateEnum;
import org.seckill.exception.RepeatkillException;
import org.seckill.exception.SeckillCloseException;
import org.seckill.exception.SeckillException;
import org.seckill.service.SeckillService;

/**
 * @ClassName:   SeckillServiceImpl
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author ：      lxp
 * @date ：        2016年9月21日 下午2:50:37
 *
 */
@Service
public class SeckillServiceImpl implements SeckillService {

    //MD5盐值字符串，用于混淆MD5
    private final String slat = "asdfdaesfdsaf!@@#@$fsdaf";
    
    private Logger logger = LoggerFactory.getLogger(getClass());
    
    @Autowired
    private SeckillDao seckillDao;
    @Autowired
    private SuccessKilledDao successkilledDao;
    
    @Autowired
    private RedisDao redisDao;
    
    
    @Override
    public List<Seckill> getSeckillList() {
        return seckillDao.queryAll(0, 4);
    }

    @Override
    public Seckill getById(long seckillId) {
        return seckillDao.queryById(seckillId);
    }

    @Override
    public Exposer exportSeckillUrl(long seckillId) {
        //优化点缓存优化：超时基础上维护一致性
        //1.访问redis
        Seckill seckill = redisDao.getSeckill(seckillId);
        if(null == seckill){
            //2.访问数据库
             seckill = seckillDao.queryById(seckillId);
             if(null == seckill){
                 return new Exposer(false, seckillId);
             }else{
                 //3.放入redis缓存
                 redisDao.putSeckill(seckill);
             }
        }
        Date startTime = seckill.getStartTime();
        Date endTime = seckill.getEndTime();
        //系统当前时间
        Date nowTime = new Date();
        if (nowTime.getTime() < startTime.getTime() || nowTime.getTime() > endTime.getTime()) {
            return new Exposer(false, seckillId, nowTime.getTime(), startTime.getTime(), endTime.getTime());
        }
        //转化特定字符串的过程，不可逆
        String md5 = getMD5(seckillId);
        return new Exposer(true, md5, seckillId);
    }

    @Transactional
    /**
     * 使用注解控制事务方法的优点；
     * 1：开发团队达成一致约定，明确标注事务方法的编程风格
     * 2：保证事务方法的执行时间尽可能短，不要穿插其他的网络操作请求
     * 3：不是所有的方法都要事务，如只有一条修改操作，或者只读操作
     */
    public SeckillExecution executeSeckill(long seckillId, long userPhone, String md5) throws SeckillException, SeckillCloseException, RepeatkillException {
        if (md5 == null || !md5.equals(getMD5(seckillId))) {
            throw new SeckillException("seckill data rewrite");
        }
        //执行秒杀逻辑减库存，记录购买行为
        Date nowTime = new Date();
        try {
            //记录购买行为
            int insertCoun = successkilledDao.insertSuccessKilled(seckillId, userPhone);
            //唯一seckillId,userPhone
            if (insertCoun <= 0) {
                //重复秒杀
                throw new RepeatkillException("seckill repeated");
            } else {
                //减库存,热点商品竞争
                int updateCount = seckillDao.reduceNumber(seckillId, nowTime);
                if (updateCount < 0) {
                    //没有跟新到记录,秒杀结束,rollback
                    throw new SeckillCloseException("seckill is closed");
                } else {
                    //秒杀成功,commit
                    Successkilled successKilled = successkilledDao.queryByIdWithSeckill(seckillId, userPhone);
                    return new SeckillExecution(seckillId, SeckillStateEnum.SUCCESS, successKilled);
                }
            }
        } catch (SeckillCloseException e1) {
            throw e1;
        } catch (RepeatkillException e2) {
            throw e2;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            //所有编译器异常转化成运行期异常
            throw new SeckillException("seckill inner error:" + e.getMessage());
        }
    }

    @Override
    public SeckillExecution executeSeckillProcedure(long seckillId, long userPhone, String md5) {
        if (md5 == null || !md5.equals(getMD5(seckillId))) {
            return new SeckillExecution(seckillId, SeckillStateEnum.DATA_REWRITE);
        }
        Date killTime = new Date();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("seckillId", seckillId);
        map.put("phone", userPhone);
        map.put("killTime", killTime);
        map.put("result", null);
        //执行存储过程之后，result 被赋值
        try {
            seckillDao.killByProcedure(map);
            //获取result
            int result = MapUtils.getInteger(map, "result", -2);
            if (result == 1) {
                Successkilled sk = successkilledDao.queryByIdWithSeckill(seckillId, userPhone);
                return new SeckillExecution(seckillId, SeckillStateEnum.SUCCESS, sk);
            } else {
                return new SeckillExecution(seckillId, SeckillStateEnum.stateOf(result));
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return new SeckillExecution(seckillId, SeckillStateEnum.INNER_ERROR);
        }
    }
  //生成md5
    private String getMD5(long seckillId) {
        String base = seckillId + "/" + slat;
        //生成MD5工具类
        String md5 = DigestUtils.md5DigestAsHex(base.getBytes());
        return md5;
    }

}
